<template>
  <page-container :title="false" :breadcrumb="false">
    <div class="box-container">
      <a-form-model layout="inline" :model="queryParams">
        <a-form-model-item label="部门名称">
          <a-input v-model="queryParams.positionName" allow-clear />
        </a-form-model-item>
        <a-form-model-item label="部门状态">
          <a-select v-model="queryParams.status" style="width: 160px" allow-clear>
            <a-select-option v-for="item in stateTypeList" :key="item.id" :value="item.dictValue" allow-clear>
              {{ item.dictLabel }}
            </a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item>
          <a-button
            icon="search"
            html-type="submit"
            @click="getTableDataByFirst"
          >
            查询
          </a-button>
        </a-form-model-item>
      </a-form-model>
    </div>

    <div class="mt10">
      <div class="table_title_operate">
        <div class="left">
          <a-button
            type="primary"
            plain
            @click="onOpenAddDeptModal"
          >新增部门</a-button>
        </div>
      </div>

      <s-table
        ref="table"
        class="bg-white"
        row-key="id"
        :columns="tableParams.columns"
        :data="tableParams.loadData"
        :row-selection="{ selectedRowKeys: tableParams.rowSelection.selectedRowKeys, onChange: tableParams.rowSelection.onChange }"
        :init-request="tableParams.initRequest"
        :show-pagination="false"
      >
        <span slot="status" slot-scope="text">
          <a-badge v-if="text === 'ENABLE'" status="success" text="启用" />
          <a-badge v-else status="error" text="停用" />
        </span>
        <span slot="remark" slot-scope="text">
          <text-tooltip :content="text" />
        </span>
        <span slot="operate" slot-scope="text, record, index">
          <template>
            <a @click="onOpenModifyDeptModal(index, record)">修改</a>
            <a-divider type="vertical" />
            <a @click="onDeleteDept(index, record)">删除</a>
          </template>
        </span>
      </s-table>
    </div>

    <a-modal v-model="open" :title="title">
      <a-form-model ref="deptForm" :model="deptForm" :rules="deptFormRules">
        <a-row>
          <a-col :span="24">
            <a-form-item prop="parentId" label="上级部门" :label-col="{ span: 4 }" :wrapper-col="{span:20}">
              <treeselect v-model="deptForm.parentId" :normalizer="normalizer" placeholder="请选择上级部门" :options="deptTree" :show-count="true" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item prop="name" label="部门名称" :label-col="{ span: 8 }" :wrapper-col="{span:16}">
              <a-input v-model="deptForm.name" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item prop="treeSort" label="显示排序" :label-col="{ span: 8 }" :wrapper-col="{span:16}">
              <a-input-number v-model="deptForm.treeSort" style="width: 100%" :min="1" :max="10" />
            </a-form-item>
          </a-col>

          <a-col :span="24">
            <a-form-item label="部门状态" :label-col="{ span: 4 }" :wrapper-col="{span:20}">
              <a-radio-group v-model="deptForm.status">
                <a-radio v-for="item in stateTypeList" :key="item.id" :value="item.dictValue">{{ item.dictLabel }}</a-radio>
              </a-radio-group>
            </a-form-item>
          </a-col>

          <a-col :span="24">
            <a-form-item label="备注" :label-col="{ span: 4 }" :wrapper-col="{span:20}">
              <a-input v-model="deptForm.remark" type="textarea" :rows="3" />
            </a-form-item>
          </a-col>
        </a-row>

      </a-form-model>

      <template slot="footer">
        <a-button key="back" @click="open = false">
          取消
        </a-button>

        <template v-if="!deptForm.id">
          <!--新增-->
          <a-button key="submit" type="primary" @click="onAddOrModifyDept">确认</a-button>
        </template>
        <template v-else>
          <!--修改-->
          <a-button key="submit" type="primary" @click="onAddOrModifyDept">确认</a-button>
        </template>

      </template>
    </a-modal>
  </page-container>
</template>

<script>
// import the component
import Treeselect from '@riophae/vue-treeselect'
// import the styles
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import { parseTime, debounce, deleteNullChildren } from '@/utils'
import { getDeptTreeApi, getTreeByEntityApi, addDeptApi, modifyDeptApi, deleteDeptApi } from '@/api/system/dept'

export default {
  name: 'Dept',
  components: { Treeselect },
  data() {
    const columns = [
      {
        title: '部门名称',
        dataIndex: 'name'
      },
      {
        title: '显示排序',
        dataIndex: 'treeSort'
      },
      {
        title: '部门状态',
        dataIndex: 'status',
        scopedSlots: { customRender: 'status' }
      },
      {
        title: '创建时间',
        dataIndex: 'createDate',
        customRender(createDate) {
          return parseTime(createDate)
        }
      },
      {
        title: '备注',
        dataIndex: 'remark',
        width: '150px',
        scopedSlots: { customRender: 'remark' }
      },
      {
        title: '操作',
        dataIndex: 'operate',
        scopedSlots: { customRender: 'operate' }
      }
    ]

    return {
      // 状态字典
      stateTypeList: [],
      queryParams: {
        name: undefined,
        status: undefined
      },

      tableParams: {
        pagination: false,
        columns,
        loadData: parameter => {
          const requestParameters = Object.assign({}, parameter, this.$parseQueryParams(this.queryParams))
          return getTreeByEntityApi(requestParameters)
            .then(res => {
              return deleteNullChildren(res.data)
            })
        },
        rowSelection: {
          selectedRowKeys: [],
          onChange: this.onSelectChange
        },
        selectedRowKeys: [],
        selectedRows: [],
        initRequest: true
      },

      title: '',
      open: false,
      deptForm: {},
      deptFormRules: {
        parentId: [
          { required: true, message: '上级部门不能为空', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '部门名称不能为空', trigger: 'blur' }
        ],
        treeSort: [
          { required: true, message: '显示排序不能为空', trigger: 'blur' }
        ]
      },
      deptTree: [],
      normalizer(node) {
        return {
          id: node.id,
          label: node.name,
          children: node.children
        }
      }
    }
  },
  created() {
    this.initDict()
    this.getTableDataByFirst()
  },
  methods: {
    getTableDataByFirst() {
      this.$refs.table && this.$refs.table.refresh(true)
    },

    /**
     * 初始化数据字典
     */
    initDict() {
      this.$getCodeDictMap(this, {
        STATUS_TYPE: 'stateTypeList'
      })
    },

    /**
     * 重置部门添加或修改表单
     */
    resetDeptForm() {
      this.deptForm = {
        id: undefined,
        parentId: undefined,
        name: undefined,
        status: 'ENABLE',
        remark: undefined,
        treeSort: undefined
      }
      // this.$resetForm('deptForm')
    },

    /**
     * 打开新增部门弹窗
     * @param index 当前索引
     * @param row 当前部门数据
     */
    onOpenAddDeptModal(index, row) {
      this.resetDeptForm()
      this.onGetDeptTreeData()
      if (row) {
        this.deptForm.parentId = row.id
      }
      this.title = '新增部门'
      this.open = true
    },

    /**
     * 打开修改部门弹窗
     * @param index 当前索引
     * @param row 当前部门数据
     */
    onOpenModifyDeptModal(index, dept) {
      this.resetDeptForm()
      this.onGetDeptTreeData()
      this.deptForm = {
        ...dept
      }
      this.title = '修改部门'
      this.open = true
    },

    /**
     * 获取部门tree数据
     */
    onGetDeptTreeData() {
      getDeptTreeApi({}).then((res) => {
        if (res && res.code === 'A00000') {
          this.deptTree = this.$deleteNullChildren(res.data)
          console.log(this.deptTree)
        }
      })
    },

    /**
     * 新增或修改部门信息
     */
    onAddOrModifyDept: debounce(function() {
      this.$refs.deptForm.validate((valid) => {
        if (valid) {
          const params = {
            id: this.deptForm.id,
            parentId: this.deptForm.parentId,
            name: this.deptForm.name,
            status: this.deptForm.status,
            remark: this.deptForm.remark,
            treeSort: this.deptForm.treeSort
          }

          // 新增部门
          if (this.deptForm.id === undefined) {
            addDeptApi(params).then((res) => {
              if (res && res.code === 'A00000') {
                this.open = false
                this.$message.success(res.msg)
                this.getTableDataByFirst()
              } else {
                this.$message.error(res.msg)
              }
            })
          } else {
            // 修改部门
            modifyDeptApi(params).then((res) => {
              if (res && res.code === 'A00000') {
                this.open = false
                this.$message.success(res.msg)
                this.getTableDataByFirst()
              } else {
                this.$message.error(res.msg)
              }
            })
          }
        }
      })
    }),

    /**
     * 删除部门数据
     */
    onDeleteDept(index, post) {
      this.$confirm({
        title: '提示',
        content: '确认删除当前部门, 是否继续?',
        okText: '确定',
        cancelText: '取消',
        type: 'warning',
        onOk: () => {
          deleteDeptApi(post).then((res) => {
            if (res && res.code === 'A00000') {
              this.getTableDataByFirst()
              this.$message.success(res.msg)
            } else {
              this.$message.error(res.msg)
            }
          })
        }
      })
    },

    /**
     * 表格多选示例
     * @param selectedRowKeys
     * @param selectedRows
     */
    onSelectChange(selectedRowKeys, selectedRows) {
      this.tableParams.rowSelection.selectedRowKeys = selectedRowKeys

      // this.tableParams.selectedRowKeys = selectedRowKeys
      // this.tableParams.selectedRows = selectedRows
    }
  }
}
</script>
<style scoped>
/** 全局表格头部操作 */
.table_title_operate{
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
}

</style>
